#include <stdio.h>
#include <stdlib.h>

//#include <ucontext.h>
#include <execinfo.h>
#include <signal.h>

void test_1(int *);
void test_2(int *);
void test_3(int *);

static void signal_handler(int, siginfo_t *, void *);

int main()
{
    int *p = (int *)0x12345678;

    struct sigaction action;

    sigemptyset(&action.sa_mask);
    action.sa_sigaction = signal_handler;
    action.sa_flags = SA_SIGINFO;

    sigaction(SIGSEGV, &action, NULL);

    printf(">>>> BEFORE >>>>\n");
    test_1(p);
    printf(">>>> AFTER  >>>>\n");

    return 0;
}

void test_1(int *p)
{
    test_2(p);
}

void test_2(int *p)
{
    test_3(p);
}

void test_3(int *p)
{
    *p = 1;
}

void signal_handler(int signo, siginfo_t *info, void *ctx)
{
//    ucontext_t *context = (ucontext_t *)ctx;

    printf("SIGNAL: %d", signo);
    printf(", Memory Location: %p\n", info->si_addr);
 //   printf(", RFLAGS: %016X\n", context->uc_mcontext.gregs[REG_EFL]);

    void *buf[256] = { 0 };
    int size = backtrace(buf, 256);
    backtrace_symbols_fd(buf, size, fileno(stdout));

    exit(-1);
}
